class LoggedActionsController < ApplicationController
  caches_action :graph_of_completion_times, :graph_of_db_times, :graph_of_hits, :graph_of_render_times
  
	before_filter :get_logged_controller
	before_filter :get_logged_actions, :except => [:show]
	
  def index
  	
  end
  
  def graphs
  	@graph_of_hits = open_flash_chart_object(500, 500, graph_of_hits_logged_controller_logged_actions_url)
  	@graph_of_completion_times = open_flash_chart_object(900, 300, graph_of_completion_times_logged_controller_logged_actions_url)
  	@graph_of_render_times = open_flash_chart_object(900, 300, graph_of_render_times_logged_controller_logged_actions_url)
  	@graph_of_db_times = open_flash_chart_object(900, 300, graph_of_db_times_logged_controller_logged_actions_url)
  end

  def show
  	@logged_action = @logged_controller.logged_actions.find params[:id]
  end

  def graph_of_hits
  	ofc = ofc_pie_graph_with_defaults(@collection_for_graph, 'count', 'name', "Percentage of Hits per Action",
             @collection_for_graph.map { |mem| "/log_entries?logged_action_id=#{mem.id}" })
  	render :text => ofc.render
  end
  
  def graph_of_completion_times
		ofc = ofc_bar_graph_with_defaults @logged_actions, 'average_completion_time_in_ms', 'name', 'Completion Time per Action', 
						'Average Time to Complete (in milliseconds) by Action' 
    render :text => ofc.render
	end
  
  def graph_of_render_times
		ofc = ofc_bar_graph_with_defaults @logged_actions, 'average_render_time_in_ms', 'name', 'Render Time per Action', 
						'Average Time to Render (in milliseconds) by Action' 
    render :text => ofc.render
  end
  
  def graph_of_db_times
  	ofc = ofc_bar_graph_with_defaults @logged_actions, 'average_db_time_in_ms', 'name', 'DB Access Time per Action', 
  					'Average DB Access Time (in milliseconds) by Action' 
    render :text => ofc.render
  end
  
  
  private
 	
 	def get_logged_controller
 		@logged_controller = LoggedController.find params[:logged_controller_id]
 	end
 	
 	def get_logged_actions
	 	@logged_actions = @logged_controller.logged_actions
    sum_of_hits = @logged_actions.map(&:count).compact.sum.to_f
    @collection_for_graph, @other_actions = @logged_actions.partition { |c| (c.count / sum_of_hits) > 0.01 }
    if @other_actions.size > 1
      @collection_for_graph << LoggedController.new( :count => @other_actions.map(&:count).sum, 
        :name => "Other")
    elsif @other_actions.size == 1
      @collection_for_graph << @other_actions.first
    end
	end
end
